package flc.ast.activity;

import android.app.Dialog;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelDocAdapter;
import flc.ast.bean.MyDocBean;
import flc.ast.databinding.ActivityDocManageBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.MediaInfo;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;

public class DocManageActivity extends BaseAc<ActivityDocManageBinding> {

    private List<MyDocBean> listShow = new ArrayList<>();
    private List<MyDocBean> listDelete = new ArrayList<>();
    private SelDocAdapter selDocAdapter;
    private Dialog myRenameDialog;
    private boolean isEdit = false;
    private boolean isSelectAll = false;
    private int selPosition;
    private AttachPopupView attachPopupView;
    private EditText editText;

    @Override
    protected int onCreate() {
        return R.layout.activity_doc_manage;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivDocManageBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.rvDocList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        selDocAdapter = new SelDocAdapter();
        mDataBinding.rvDocList.setAdapter(selDocAdapter);
        selDocAdapter.addChildClickViewIds(R.id.ivSelDocItemEdit);
        selDocAdapter.setOnItemChildClickListener(this);
        selDocAdapter.setOnItemClickListener(this);
        selDocAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (!isEdit) {
                    isEdit = true;
                    selDocAdapter.setEdit(isEdit);
                    selDocAdapter.notifyDataSetChanged();
                    mDataBinding.tvSelNum.setVisibility(View.VISIBLE);
                    mDataBinding.llDocManageBottom.setVisibility(View.VISIBLE);
                } else {
                    listDelete.clear();
                    isEdit = false;
                    selDocAdapter.setEdit(isEdit);
                    getData();
                    mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listDelete.size()));
                    mDataBinding.tvSelNum.setVisibility(View.GONE);
                    mDataBinding.llDocManageBottom.setVisibility(View.GONE);
                }
                return true;
            }
        });
        mDataBinding.llSelectAll.setOnClickListener(this);
        mDataBinding.llDelete.setOnClickListener(this);
        mDataBinding.llShare.setOnClickListener(this);
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.llSelectAll://全选
                listDelete.clear();
                if (isSelectAll) {
                    for (MyDocBean validDatum : selDocAdapter.getValidData()) {
                        validDatum.setSelect(false);
                    }
                } else {
                    for (MyDocBean validDatum : selDocAdapter.getValidData()) {
                        validDatum.setSelect(true);
                        listDelete.add(validDatum);
                    }
                }
                isSelectAll();
                selDocAdapter.notifyDataSetChanged();
                break;
            case R.id.llDelete://删除
                if (listDelete.size() == 0) {
                    return;
                }
                delete();
            case R.id.llShare://分享
                share();
                break;
            //重命名
            case R.id.ivDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                FileUtils.rename(selDocAdapter.getItem(selPosition).getPath(), name + "." + FileUtils.getFileExtension(selDocAdapter.getItem(selPosition).getPath()));
                myRenameDialog.dismiss();
                editText.setText("");
                getData();
                break;
            case R.id.ivDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (isEdit) {
            if (selDocAdapter.getItem(position).isSelect()) {
                selDocAdapter.getItem(position).setSelect(false);
                listDelete.remove(selDocAdapter.getItem(position));
                selDocAdapter.notifyDataSetChanged();
            } else {
                listDelete.add(selDocAdapter.getItem(position));
                selDocAdapter.getItem(position).setSelect(true);
                selDocAdapter.notifyDataSetChanged();
            }
            isSelectAll();
        } else {
            IntentUtil.openDoc(mContext, selDocAdapter.getItem(position).getPath());
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        selPosition = position;
        switch (view.getId()) {
            case R.id.ivSelDocItemEdit:
                attachPopupView = new XPopup.Builder(mContext)
                        .hasShadowBg(false)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isDarkTheme(true)
//                        .popupAnimation(PopupAnimation.NoAnimation) //NoAnimation表示禁用动画
//                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                        .offsetY(-60)
//                        .offsetX(80)
                        .popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{getString(R.string.delete), getString(R.string.share), getString(R.string.rename)},
                                new int[]{R.drawable.ashanchu3, R.drawable.afenx, R.drawable.achongmm},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        switch (position) {
                                            case 0:
                                                delete();
                                                break;
                                            case 1:
                                                IntentUtil.shareFile(mContext, selDocAdapter.getItem(selPosition).getPath());
                                                break;
                                            case 2:
                                                myRenameDialog.show();
                                                break;
                                        }
                                    }
                                }, 0, 0);
                ;
//                }
                attachPopupView.show();
                break;
        }
    }

    @Override
    protected void initData() {
        mDataBinding.tvSelNum.setVisibility(View.GONE);
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, 0));
        getData();
    }

    //获取文档数据
    private void getData() {
        //设置获取的数据类型 只获取pdf
        List<String> type = new ArrayList<>();
        type.add("application/msword");
        type.add("application/vnd.ms-excel");
        type.add("application/vnd.ms-powerpoint");
        type.add("application/pdf");
        type.add("text/plain");
        listShow.clear();
        RxUtil.create(new RxUtil.Callback<List<MediaInfo>>() {
            @Override
            public void doBackground(ObservableEmitter<List<MediaInfo>> emitter) {
                List<MediaInfo> infoList = MediaLoader.loadDoc(type);
                emitter.onNext(infoList);
            }

            @Override
            public void accept(List<MediaInfo> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    for (MediaInfo bean : selectMediaEntities) {
                        listShow.add(new MyDocBean(bean.getName(), bean.getPath(), bean.getUri()
                                , ConvertUtils.byte2FitMemorySize(bean.getSize(), 3)
                                , TimeUtils.millis2String(FileUtils.getFileLastModified(bean.getPath()), "yyyy/MM/dd"), false));
                    }
                }
                if (listShow.size() > 0) {
                    selDocAdapter.setList(listShow);
                    mDataBinding.rvDocList.setVisibility(View.VISIBLE);
                    mDataBinding.tvDocManageNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvDocList.setVisibility(View.GONE);
                    mDataBinding.tvDocManageNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void isSelectAll() {
        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listDelete.size()));
        if (listDelete.size() == selDocAdapter.getValidData().size()) {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.ayiquanx);
            isSelectAll = true;
        } else {
            mDataBinding.ivSelectAll.setImageResource(R.drawable.aquanx);
            isSelectAll = false;
        }
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        for (int i = 0; i < listDelete.size(); i++) {
                            //从此文件夹删除
                            mContext.getContentResolver().delete(Uri.parse(listDelete.get(i).getUri()), null, null);
                        }
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        listDelete.clear();
                        isEdit = false;
                        selDocAdapter.setEdit(isEdit);
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                        mDataBinding.tvSelNum.setText(getString(R.string.sel_num, listDelete.size()));
                        mDataBinding.tvSelNum.setVisibility(View.GONE);
                        mDataBinding.llDocManageBottom.setVisibility(View.GONE);
                    }
                });
            }
        }, 1000);
    }

    private void share() {
        if (listDelete.size() == 0) {
            return;
        }
        if (listDelete.size() > 1) {
            ToastUtils.showShort(getString(R.string.share_one_file));
            return;
        }
        IntentUtil.shareFile(mContext, listDelete.get(0).getPath());
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

}